import _ from 'lodash'
import { t } from '@src/locales'
import platform from '@src/platform'
import { isEmpty, isObject, isArray, isNumber, useFormTimezone } from 'pub-bbx-utils'
const { disposeFormViewTime } = useFormTimezone()

/**
 * @description 将数据转成form表单可提交的表单
 */
export function packSaveForm(fields, values) {
  let formData = [];
  const data = _.cloneDeep(values);
  fields.forEach(field => {
    let { fieldName, formType } = field;
    let value = data[fieldName];
    let fieldValue = {};
    if (isArray(value)) {
      // 如果值是数组 比如客户
      if (!value.length) {
        value = ['']
      } else {
        value = value.filter(Boolean)
        if (formType == 'user') {
          value.map(item => {
            item.id = item.userId
            item.name = item.displayName
          })
        }
        value = [JSON.stringify(value)]
      }
    } else if (isObject(value)) {
      // 如果值是对象比如人员 前端传给后端json字符串
      if(isEmpty(value)) {
        value = ['']
      } else {
        if (formType == 'user') {
          value = {
            ...value,
            id: value.userId,
            name: value.displayName
          }
        }
        value = [JSON.stringify(value)]
      }
    }
    fieldValue = {
      formType,
      fieldName,
      value,
    };
    formData.push(fieldValue)
  })
  return formData;
}

/**
 * @description 将智能计划对象转成form表单，用于初始化表单
 */
export function packToForm(formValue, fields) {
  try {
    const data = _.cloneDeep(formValue);
    let { planBasicData, planRange, allotSetting, startSetting, endSetting, periodSetting } = data
    data.planBasicData = JSON.parse(planBasicData)
    let planForm = {}
    data.planBasicData.forEach(item => {
      let value = item.value || ''
      try {
        if (isObject(value) && value) {
          value = value[0] ? JSON.parse(value[0]) : value
          if (isNumber(value)) {
            value = String(value)
          }
        }
      } catch (error) {
        console.error('packToForm planBasicData json.parse error:', error)
      }
      planForm[item.fieldName] = value
    })
    data.planForm = disposeFormViewTime(fields, planForm)
    data.planRange = JSON.parse(planRange).map(item => {
      item = item.filter(sub => {
        return !isEmpty(sub.conditionItem.value)
      })
      return item
    }).filter(item => item.length)
    data.conditions = []
    data.planRange.forEach(item => {
      data.conditions.push({
        subCondition: item
      })
    })
    data.allotSetting = JSON.parse(allotSetting)
    data.startSetting = JSON.parse(startSetting)
    data.endSetting = JSON.parse(endSetting)
    data.periodSetting = JSON.parse(periodSetting)
    // 第三步数据整合
    data.thirdForm = {
      createDimension: data.createDimension,
      startSetting: data.startSetting,
      endSetting: data.endSetting,
      periodSetting: data.periodSetting,
    }
    return data
  } catch(e) {
    console.error('packToForm error:', e)
    return {}
  }
  
}

/**
 * @description 智能计划详情列表操作
 */
export async function handleOperation(api, params, tip, callback) {
  let confirm = await platform.confirm(tip);
  if (confirm) {
    api(params).then(res => {
      let isSucc = res.success || res.succ;
    
      platform.notification({
        type: isSucc ? 'success' : 'error',
        title: isSucc ? t('common.base.tip.operationSuccess') : t('common.base.tip.operationFail'),
        message: !isSucc && res.message
      })
      if (isSucc) {
        callback && callback()
      }
    })
  }
}